package top.ochiamalu.aioj.util;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import top.ochiamalu.aioj.common.ErrorCode;
import top.ochiamalu.aioj.exception.BusinessException;
import top.ochiamalu.aioj.properties.AIOJProperties;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static top.ochiamalu.aioj.constant.SystemConstants.DEFAULT_BUFFER_SIZE;
import static top.ochiamalu.aioj.constant.SystemConstants.FILE_END;

/**
 * 文件工具类
 *
 * @author ochiamalu
 * @date 2025/02/10
 */
@Component
@Slf4j
public class FileUtils {

    private static AIOJProperties aiojProperties;

    @Resource
    private AIOJProperties tempProperties;

    /**
     * 上传文件到本地
     *
     * @param file 文件
     * @return {@link String}
     */
    public static String uploadFile2Local(MultipartFile file) {
        File localFile = transferFile(file);
        return localFile.getName();
    }

    /**
     * 上传文件到云端
     *
     * @param file 文件
     * @return {@link String}
     */
    public static String uploadFile2Cloud(MultipartFile file) {
        File localFile = transferFile(file);
        byte[] imageStream = getImageStream(localFile);
        String fileName = QiNiuUtils.upload(imageStream);
        boolean delete = localFile.delete();
        if (!delete) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        //上传七牛云
        return fileName;
    }

    /**
     * 获取图像流
     *
     * @param imageFile 图像文件
     * @return {@link byte[]}
     */
    public static byte[] getImageStream(File imageFile) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             FileInputStream fis = new FileInputStream(imageFile)) {
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int n;
            while ((n = fis.read(buffer)) != FILE_END) {
                bos.write(buffer, 0, n);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            log.error("Failed to read file stream", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 传输文件
     *
     * @param file 文件
     * @return {@link File}
     */
    public static File transferFile(MultipartFile file) {
        String uid = UUID.randomUUID().toString(true);
        //获取原文件名
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (StringUtils.isEmpty(suffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Path dirPath = Paths.get(System.getProperty("user.dir"), aiojProperties.getImg()).toAbsolutePath().normalize();
        //如果文件夹不存在则新建文件夹
        if (!Files.exists(dirPath)) {
            try {
                Files.createDirectories(dirPath);
            } catch (IOException e) {
                log.error("Failed to create directory", e);
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
        File localFile = new File(dirPath.toString(), uid + suffix);
        try {
            //将文件从tomcat临时目录转移到指定的目录
            file.transferTo(localFile);
        } catch (IOException e) {
            log.error("Failed to transfer file", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        String newFileName = DigestUtil.md5Hex(localFile) + suffix;
        File newFile = new File(dirPath.toString(), newFileName);
        if (newFile.exists()) {
            boolean deleted = localFile.delete();
            if (!deleted) {
                log.error("Failed to delete existing file");
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } else {
            boolean renamed = localFile.renameTo(newFile);
            if (!renamed) {
                log.error("Failed to rename file");
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
        return newFile;
    }

    @PostConstruct
    public void init() {
        aiojProperties = tempProperties;
    }
}
